package com.junyue.control.platform;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.junyue.control.platform.entity.*;
import com.junyue.control.platform.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping({"/index"})
public class IndexController {
    @Autowired
    ConfigBeanValue configBeanValue;

    @RequestMapping({"/read"})
    public void readSetting() {
        Map<String, String> map = new HashMap();
        String data = ReadFileUtils.readFileByLines(configBeanValue.getFilePath());
        String temp = data.replaceAll("\t", "");
        List<ControlData> controlDataList = JSONArray.parseArray(temp, ControlData.class);
        System.out.println(controlDataList);
    }

    @RequestMapping({"/login"})
    public String login() {
        return "login";
    }

    @RequestMapping({"/index"})
    public String index(HttpServletRequest request) {
        return "index";
    }

    @RequestMapping({"/logout"})
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginStatus");
        return "login";
    }

    @RequestMapping({"/welcome"})
    public String welcome() {
        return "welcome";
    }

    @RequestMapping({"/copyToAddList"})
    public String toAddList(HttpServletRequest request) {
        String versionId = request.getParameter("versionId");
        Map<String, ResultData> dataMap = FileToData.getVersionMapData(configBeanValue.getFilePath());
        if (dataMap.containsKey(versionId)) {
            ResultData resultData = (ResultData) dataMap.get(versionId);
            request.setAttribute("version", resultData.getData().getVersion());
            request.setAttribute("packageName", resultData.getData().getPackageName());
            request.setAttribute("appType", resultData.getData().getAppType());
            request.setAttribute("versionId", versionId);
            request.setAttribute("check", true);
        }
        return "addList";
    }

    @RequestMapping({"/toAddList"})
    public String toAddList() {
        return "addList";
    }

    @RequestMapping({"/versionAdd"})
    public String versionAdd() {
        return "versionAdd";
    }

    @RequestMapping({"/versionEdit"})
    public String versionEdit(HttpServletRequest request) {
        String versionName = request.getParameter("versionName");
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        if (dataMap.containsKey(versionName)) {
            request.setAttribute("data", JSONObject.toJSON(dataMap.get(versionName)));
        } else {
            request.setAttribute("data", "");
        }
        request.setAttribute("versionName", versionName);
        return "versionEdit";
    }

    @RequestMapping({"/editList"})
    public String editList(HttpServletRequest request) {
        String versionName = request.getParameter("versionName");
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        if (dataMap.containsKey(versionName)) {
            request.setAttribute("data", JSONObject.toJSON(dataMap.get(versionName)));
        } else {
            request.setAttribute("data", "");
        }
        request.setAttribute("versionName", versionName);
        return "editList";
    }

    @ResponseBody
    @RequestMapping({"/addVerion"})
    public ResultMessage addVerion(HttpServletRequest request) {
        boolean check = false;
        String data = request.getParameter("data");
        ResultMessage resultMessage = new ResultMessage();
        ListData listData = JSONObject.parseObject(data, ListData.class);
        String versionName = listData.getPackageName() + "-" + listData.getAppType() + "-" + listData.getVersion();
        Map<String, ResultData> currentMap = FileToData.getMapData(configBeanValue.getFilePath());
        if (null != listData.getCheck() && "on".equals(listData.getCheck())) {
            check = true;
        }
        if (!check&&currentMap.containsKey(versionName)) {
            resultMessage.setStatus(false);
            resultMessage.setMessage("添加失败，版本号重复!");
        } else {
            if ((listData.getVersionId() != null) && (!listData.getVersionId().isEmpty())) {
                Map<String, ResultData> dataMap = FileToData.getVersionMapData(configBeanValue.getFilePath());
                if (dataMap.containsKey(listData.getVersionId())) {
                    ResultData resultData = (ResultData) dataMap.get(listData.getVersionId());
                    resultData.getData().setVersionId(UUID.randomUUID().toString());
                    resultData.getData().setVersion(listData.getVersion());
                    resultData.getData().setCreateTime(DateTimeUtils.getCurrentDataTime());
                    resultData.getData().setAppId(UUID.randomUUID().toString());
                    resultData.getData().setPackageName(listData.getPackageName());
                    resultData.getData().setAppType(listData.getAppType());

                    Map<String, ResultData> oldDataMap = FileToData.getMapData(configBeanValue.getFilePath());
                    oldDataMap.put(versionName, resultData);
                    CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), oldDataMap, CommonUtils.MapToList(oldDataMap));
                }
                resultMessage.setStatus(true);
                resultMessage.setMessage("添加成功!");
                return resultMessage;
            }
            VersionData versionData = new VersionData();
            versionData.setVersion(listData.getVersion());
            versionData.setPackageName(listData.getPackageName());
            versionData.setAppType(listData.getAppType());
            versionData.setAppId(UUID.randomUUID().toString());
            versionData.setSwitchData(new ArrayList());
            versionData.setUuid(1);
            versionData.setVersionId(UUID.randomUUID().toString());
            versionData.setCreateTime(DateTimeUtils.getCurrentDataTime());
            ResultData resultData = new ResultData();
            resultData.setCode(1);
            resultData.setMessage("success");
            resultData.setData(versionData);
            Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
            dataMap.put(versionName, resultData);
            CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), dataMap, CommonUtils.MapToList(dataMap));

            resultMessage.setStatus(true);
            resultMessage.setMessage("添加成功!");
        }

        return resultMessage;
    }

    @ResponseBody
    @RequestMapping({"/saveList"})
    public ResultMessage saveList(HttpServletRequest request) {
        String data = request.getParameter("data");
        ResultMessage resultMessage = new ResultMessage();
        if ((data != null) && (!data.isEmpty())) {
            ListData listData = (ListData) JSONObject.parseObject(data, ListData.class);
            Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
            if (dataMap.containsKey(listData.getOldVersionName())) {
                ResultData resultData = (ResultData) dataMap.get(listData.getOldVersionName());
                resultData.getData().setAppType(listData.getAppType());
                resultData.getData().setPackageName(listData.getPackageName());
                resultData.getData().setVersion(listData.getVersion());
                String newVersionName = listData.getPackageName() + "-" + listData.getAppType() + "-" + listData.getVersion();
                // List<ControlData> controlDataList = new ArrayList();
                for (String key : dataMap.keySet()) {
                    if ((key.equals(listData.getOldVersionName())) &&
                            (dataMap.remove(key, dataMap.get(key)))) {
                        dataMap.put(newVersionName, resultData);
                        break;
                    }
                }
                CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), dataMap, CommonUtils.MapToList(dataMap));
            }
            resultMessage.setMessage("操作成功!");
            resultMessage.setStatus(true);
            return resultMessage;
        }
        resultMessage.setMessage("操作失败，请重试!");
        resultMessage.setStatus(false);
        return resultMessage;
    }

    @RequestMapping({"/versionSwitch"})
    public String versionSwitch(HttpServletRequest request) {
        String versionName = request.getParameter("versionName");
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        if (dataMap.containsKey(versionName)) {
            request.setAttribute("data", JSONObject.toJSON(dataMap.get(versionName)));
        } else {
            request.setAttribute("data", "");
        }
        request.setAttribute("versionName", versionName);
        return "versionSwitch";
    }

    @ResponseBody
    @RequestMapping({"/saveSwitch"})
    public ResultMessage saveSwitch(String versionName, String data) {
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        ResultMessage resultMessage = new ResultMessage();
        if (dataMap.containsKey(versionName)) {
            List<SwitchData> resultDataList = JSONArray.parseArray(data, SwitchData.class);
            ResultData resultData = dataMap.get(versionName);
            resultData.getData().setSwitchData(resultDataList);
            dataMap.put(versionName, resultData);
            CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), dataMap, CommonUtils.MapToList(dataMap));
            resultMessage.setStatus(true);
            resultMessage.setMessage("保存成功!");
            return resultMessage;
        }
        resultMessage.setMessage("保存失败，请重试!");
        return resultMessage;
    }

    //列表查询
    @RequestMapping({"/versionList"})
    public String versionList(HttpServletRequest request) {
        //平台类型
        String platform = request.getParameter("platform");
        String data = FileToData.getStringData(configBeanValue.getFilePath());
        if (!data.isEmpty()) {
            String replaceData = data.replaceAll("\t", "");
            List<ControlData> controlDataList = JSONArray.parseArray(replaceData, ControlData.class);
            List<ControlData> currentList = new ArrayList<>();
            // 所有数据进行遍历 进行平台区分
            for (ControlData controlData : controlDataList) {
                if (controlData.getResultData().getData().getAppType().equals(platform))
                    currentList.add(controlData);
            }
            if (currentList.size() == 0)
                request.setAttribute("data", new ArrayList<>());
            else {
                //按照版本号进行排序
                Collections.sort(currentList, (controlData1, controlData2) -> {
                    int version1 = 0, version2 = 0;
                    if (controlData1 != null && controlData1.getResultData().getData().getVersion() != null)
                        version1 = Integer.parseInt(controlData1.getResultData().getData().getVersion().replace(".", ""));
                    if (controlData2 != null && controlData2.getResultData().getData().getVersion() != null)
                        version2 = Integer.parseInt(controlData2.getResultData().getData().getVersion().replace(".", ""));
                    return version2 - version1;
                });
                request.setAttribute("data", currentList);
            }

        } else {
            request.setAttribute("data", new ArrayList<>());

        }
        request.setAttribute("platform", platform);
        return "versionList";
    }

    @ResponseBody
    @RequestMapping({"/deleteVersion"})
    public ResultMessage deleteVersion(String mapKey) {
        ResultMessage resultMessage = new ResultMessage();
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        if (dataMap.containsKey(mapKey)) {
            ResultData resultData = dataMap.get(mapKey);
            if (dataMap.remove(mapKey, resultData)) {
                List<ControlData> controlDataList = new ArrayList();
                for (String key : dataMap.keySet()) {
                    ControlData controlData = new ControlData();
                    controlData.setVersionName(key);
                    controlData.setResultData(dataMap.get(key));
                    controlDataList.add(controlData);
                }
                CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), dataMap, controlDataList);
                resultMessage.setStatus(true);
                resultMessage.setMessage("删除成功!");
            } else {
                resultMessage.setStatus(false);
                resultMessage.setMessage("删除失败，请重试!");
            }
        }


        return resultMessage;
    }

    /**
     * 批量删除
     *
     * @param delIds
     * @return
     */
    @ResponseBody
    @RequestMapping({"/deleteByIds"})
    public ResultMessage deleteByIds(String delIds) {
        String[] delIdsArray = delIds.split(",");
        ArrayList<String> idsList = new ArrayList<>(Arrays.asList(delIdsArray));
        ResultMessage resultMessage = new ResultMessage();
        Map<String, ResultData> dataMap = FileToData.getMapData(configBeanValue.getFilePath());
        List<String> keyList = new ArrayList();
        dataMap.forEach((k, v) -> {
            if (dataMap.get(k) != null && idsList.size() != 0) {
                if (idsList.contains(dataMap.get(k).getData().getVersionId())) {
                    keyList.add(k);
                }
            }

        });
        for (String key : keyList) {
            dataMap.remove(key);
            idsList.clear();
        }
        CommonUtils.WriteFileAndRefresh(configBeanValue.getFilePath(), dataMap, CommonUtils.MapToList(dataMap));
        if (idsList.size() == 0) {
            resultMessage.setStatus(true);
            resultMessage.setMessage("删除成功!");
        } else {
            resultMessage.setStatus(false);
            resultMessage.setMessage("删除失败，请重试!");
        }
        return resultMessage;
    }
}
